package com.zxy.controlcenter.core.shiro;


import com.zxy.controlcenter.core.exception.BizExceptionEnum;
import com.zxy.controlcenter.core.exception.ServiceException;
import com.zxy.controlcenter.modular.system.model.Admin;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;

/**
 * shiro 工具类
 *
 * @author zxy
 */
public class ShiroKit {

    final static int HASH_ITERATIONS = 1024;

    final static String HASH_ALGORITHM_NAME = "MD5";

    /**
     * 获取当前 Subject
     *
     * @return Subject
     */
    public static Subject getSubject() {
        return SecurityUtils.getSubject();
    }

    /**
     * 认证通过或已记住的用户。与guset搭配使用。
     *
     * @return 用户：true，否则 false
     */
    public static boolean isUser() {
        return getSubject() != null && getSubject().getPrincipal() != null;
    }

    /**
     * 验证当前用户是否为“访客”，即未认证（包含未记住）的用户。用user搭配使用
     *
     * @return 访客：true，否则false
     */
    public static boolean isGuest() {
        return !isUser();
    }

    public static ShiroUser createShiroUser(Admin admin) {
        ShiroUser shiroUser = new ShiroUser();
        if (admin != null) {
            shiroUser.setMobile(admin.getMobile());
            shiroUser.setId(admin.getId());
            shiroUser.setUserName(admin.getName());
            shiroUser.setPassword(admin.getPassword());
        }
        return shiroUser;
    }

    /**
     * 获取ShiroUser，不为空的
     *
     * @return ShiroUser
     */
    public static ShiroUser getUserNotNull() {
        if (isGuest()) {
            throw new ServiceException(BizExceptionEnum.NOT_LOGIN);
        } else {
            return (ShiroUser) getSubject().getPrincipals().getPrimaryPrincipal();
        }
    }

    /**
     * 从shiro获取session
     */
    public static Session getSession() {
        return getSubject().getSession();
    }

    /**
     * 获取封装的 ShiroUser
     *
     * @return ShiroUser
     */
    public static ShiroUser getUser() {
        if (isGuest()) {
            return null;
        } else {
            return (ShiroUser) getSubject().getPrincipals().getPrimaryPrincipal();
        }
    }
}
